//index.js
//获取应用实例
const app = getApp()
var f = require('../../utils/files.js');
var tools = require('../../utils/tools.js');


Page({




  data: {
    'upyunDomain':'',   //upyun域名

    'currentCity':'',   //当前选择的城市信息

    //初始化搜索值
    "search": '',  

    // 顶部广告栏 swiper 图片及id数组
    swiperImgs:[      
      app.globalData.upyunDomain + '/7.jpg',
      app.globalData.upyunDomain + '/6.jpg',
      app.globalData.upyunDomain + '/5.jpg'
    ],
    swiperIds:[3,5,6],


    //按商户或商品展示
    StoreOrGoods_arr: [{ name: '按商品或服务展示', value: 'goods' }, { name: '按商户展示', value: 'store' }],       
    StoreOrGoods_index: 1,


    //商品分类
    "g1": [
      { name: "全部" },
      { name: "男装", g2: [{ name: '男上衣', g3: [{ name: '男外套' }, { name: '男皮衣' }] }, { name: '男内衣', g3: [{ name: '男睡衣' }, { name: '男背心' }] }] },
      { name: "女装", g2: [{name:'全部'},{ name: '女上衣', g3: [{ name: '全部' },{ name: '女外套' }, { name: '女皮衣' }] }, { name: '女内衣', g3: [{ name: '女睡衣' }, { name: '女背心' }] }] },
      { name: "童装", g2: [{ name: '童上衣', g3: [{ name: '童外套' }, { name: '童皮衣' }] }, { name: '童内衣', g3: [{ name: '童睡衣' }, { name: '童背心' }] }]},
    ],       //初始化商品分类数据
    "g1_index": 0,  //初始化一级分类下标
    "g2_index": 0,  //初始化二级分类下标
    "g3_index": 0,  //初始化三级分类下标


    //商品或商户列表
    list: [], 
    searchList:[],  //带搜索的商品或商户列表

    listMax: 3,  //展示列表的最大下标

    NullNotice:true,



  },


  //点击搜索按钮
  _search() {
    var t = this

    if(t.data.search){
      var tmpList = t.data.list;
      var searchArr = [];
      for(var i=0;i<tmpList.length;i++){
        if(tmpList[i].name.indexOf(t.data.search) >= 0){
          searchArr.push(tmpList[i]);
        }
      }
    }
    app.C(searchArr);
    t.setData({
      listMax: 3,
      searchList: searchArr
    })
  },


  onLoad: function () {
  },
  onShow() {
    var t = this

    //当前城市数据
    t.setData({
      currentCity: app.globalData.currentCity,
      upyunDomain: app.globalData.upyunDomain
    })

    //获取商户列表
    t._getStoreList(function(storeList){
      if(typeof(storeList) == 'object' && storeList.length > 0){
        t.setData({
          list: storeList
        })
      }
    });
  },

  //获取商户列表
  _getStoreList(fun){
    var db_host = app.globalData.currentCity.db_host;
    var requestPath = app.globalData.currentDomain + app.globalData.default_RequestPath;
    app.Ajax2({ type:'_getStoreListAll'},function(res){
      if(fun) fun(res.data);
      app.C(res);
    })
  },

  /*
    ### 获取商户列表
    逻辑：获取全部商户列表并分页展示
      点击指定商户时，
        判断指定商户缓存是否存在 
          不在：## 远程请求商户详情
            有：添加过期标志并缓存
            无：删除全部商户列表中的相应商户
          存在：
            判断过期标志
              有效：正常显示
              过期：## 远程请求商户详情
            与本地商户信息比对
            一致：更新过期标志
            不同：

  */




  //上拉触底
  onReachBottom: function () {
    var t = this
    var max = t.data.listMax + 5
    max = max > t.data.list.length ? t.data.list.length : max
    if (max != t.data.list.length) {
      t.setData({
        listMax: max
      })
    }
  },


  //返回顶部
  _backTop(){
    app.backTop()
  },


  //商户与商品显示类型切换
  _storeOrGoodsChange(e) {
    var t = this;
    var index = e.detail.value;
    t.setData({
      StoreOrGoods_index: index,
      listMax:2   //重置展示列表的最大下标
    })
  },


  //搜索框失去焦点时获取搜索值
  _getSearchVal(e) {
    var search = e.detail.value.trim();
    this.setData({
      search: search,
      NullNotice: true
    })
  },



























  //获取商户或商品数据  参一：是否打印提示信息
  GetInfo(notice) {
    var notice = 0;

    /*
      商户字段
      $fields = 'id,banner,name,info,utag1,utag3';
                                     utag1   商户信息版本号
                                     utag3   商户下商品列表版本号
      商品字段
      $fields = '[0]id [1]banner [2]title [3]price [4]utag1 [5]s_utag1';
                                            utag1,  商品信息版本号
                                            s_utag1  关联的商户版本号

    */

    var t = this;
    t.setData({
      tmp_list: ''
    });
    var g1_index = t.data.g1_index;
    var g2_index = t.data.g2_index;
    var g3_index = t.data.g3_index;

    var goods_type1 = 'none'; //商品一级分类
    var goods_type2 = 'none'; //商品二级分类
    var goods_type3 = 'none'; //商品三级分类

    var g1 = t.data.g1;
    if (g1[g1_index].name != '全部') {
      var goods_type1 = t.data.g1[g1_index].id;
      if (g1[g1_index].g2.length > 0 && g1[g1_index].g2[g2_index].name != '全部') {
        goods_type2 = g1[g1_index].g2[g2_index].id;
        if (g1[g1_index].g2[g2_index].g3.length > 0 && g1[g1_index].g2[g2_index].g3[g3_index].name != '全部') {
          goods_type3 = g1[g1_index].g2[g2_index].g3[g3_index].id;
        }
      }
    }

    var city_code = t.data.CurrentCityCode; //县区code
    var gs_type = t.data.StoreOrGoods_index; //商品&商户
    var search = t.data.search;
    var pnow = t.data.pnow;

    //缓存文件名
    var cache_name = 's_' + city_code + '_' + gs_type + '_' + goods_type1 + '_' + goods_type2 + '_' + goods_type3 + '_' + pnow + '_' + search;
    var max_tag = 's_' + city_code + '_' + gs_type + '_' + goods_type1 + '_' + goods_type2 + '_' + goods_type3 + '_' + search;
    t.setData({
      current_page_tag: max_tag
    });
    //upyun缓存url
    var cache_path = t.data.upyun_shop_cache + '/data_cache/' + cache_name + '.html';
    //文件缓存url
    var file_path = app.globalData.data_path + escape(cache_name);

    var tmp_set = '';  //临时数据容器

    var data = {
      type: 'GetStoreOrGoodsInfoList',
      city_code: city_code,
      gs_type: gs_type,
      goods_type1: goods_type1,
      goods_type2: goods_type2,
      goods_type3: goods_type3,
      search: search,
      pnow: pnow,
      cache_name: cache_name,
    }

    wx.showLoading({
      title: 'loading .....'
    });

    var NextPageStat = false;  //用来标记文件，upyun，after获取状态标记，当都没有数据时，要返回上页，并隐藏下页

    f.Has(file_path, function (file_exists) {
      if (file_exists == 'ok') {
        f.Reads(file_path, function (file_res) {
          if (/.*"time":[0-9].*}$/.test(file_res)) { //文件数据存在
            NextPageStat = true;
            var file_res2 = JSON.parse(file_res);
            //app.C(file_res2);     
            /*
              商品列表字段  [0]id [1]banner [2]title [3]price [4]utag1 [5]s_utag1
              商户列表字段  [0]id [1]banner [2]name [3]info [4]utag1 [5]utag3
            */ 

            ParseListData(file_res2.data);
            if (file_res2.time * 1000 + t.data.file_expire > new Date().getTime()) {  //文件数据未过期
              if (notice) app.C('GetInfo file is ok');
              wx.hideLoading();
            } else {
              if (notice) app.C('GetInfo file is expire out');
              GetInfo_upyun2();
            }
          } else {
            if (notice) app.C('GetInfo file data format error')
            GetInfo_upyun2();
          }
        });
      } else {
        if (notice) app.C('GetInfo file not exists');
        GetInfo_upyun2();
      }
    });

    function GetInfo_upyun2() {
      GetInfo_upyun(function (upyun_res) {
        if (typeof upyun_res == 'object' && upyun_res.data.length > 0) {
          f.Writes2(file_path, JSON.stringify(upyun_res), function () { });
          ParseListData(upyun_res.data);
        }else{
          if (!NextPageStat){
            if(t.data.pnow == 1){
              return;
            }
            if (t.data.pnow > 1){
              var pnow = parseInt(t.data.pnow) - 1;

              //缓存当前选择条件下的最大页
              var max_tag = t.data.current_page_tag;
              var expire = 28640;                    //设置过期时间
              if(wx.getStorageSync(max_tag)){
                var tmp = wx.getStorageSync(max_tag);
                if(tmp.time < new Date().getTime()){  //过期了
                  tmp.max = pnow;
                  tmp.time = new Date().getTime() + expire;
                  app.SetStorage(max_tag, tmp);
                }
              }else{
                var tmp = {};
                tmp.time = new Date().getTime() + expire; 
                tmp.max = pnow;
                app.SetStorage(max_tag,tmp);
              }
            }else{
              var pnow = 1;
            }
            t.setData({
              pnow: pnow,
              NextStat: true
            });
            t.GetInfo();
          }else{   //删除文件缓存 (如果后台获取数据为空，则删除文件缓存)
            if (upyun_res != 'err'){
              f.DelFile(file_path,function(s){});
            }
          }
        }
      });
    }

    function GetInfo_upyun(fun) {
      app.Ajax({}, function (res_cache) {
        if (typeof res_cache == 'object' && res_cache.data.data && res_cache.data.time) { //如果upyun缓存存在
          ParseListData(res_cache.data.data);
          var cache_time = res_cache.data.time;
          var ServerZeroStamp = Math.ceil(new Date().getTime() / 1000);
          tmp_set = res_cache.data;  //将数据装载到临时容器待全部都过期且未获得数据时备用
          if (cache_time + t.data.upyun_expire > ServerZeroStamp) {  //upyun缓存未过期
            if (notice) app.C('GetInfo upyun is ok');
            wx.hideLoading();
            fun(res_cache.data);
          } else {
            if (notice) app.C('GetInfo upyun expire out');
            //后台获取数据
            GetInfo_after(function (after_data) {
              fun(after_data);
            });
          }
        } else {                                 //upyun缓存不存在
          if (notice) app.C('GetInfo upyun not exists');
          //后台获取数据
          GetInfo_after(function (after_data) {
            fun(after_data);
          });
        }
      }, cache_path, 'get', 5000);
    }

    function GetInfo_after(fun) {
      app.Ajax2(data, function (res) {
        if (typeof (res) == 'object' && res.data.data && res.data.time) {
          if (notice) app.C('GetInfo after is ok');
          fun(res.data);
        } else {
          if (notice) app.C('GetInfo after is fail');
          fun('err');
        }
        wx.hideLoading();
      }, '', 'post', 5000);
    }

    function ParseListData(data) {
      //app.C(data);
      wx.hideLoading();
      if (typeof data != 'object' || data.length < 1) {
        return;
      }
      for (var i = 0; i < data.length; i++) {
        data[i][1] = data[i][1] ? app.globalData.upyun_shop_img + data[i][1] : app.globalData.default_img;
      }
      t.setData({
        tmp_list: data
      });
    }
  },




  //跳转到地区选择页
  SelectArea() {
      wx.navigateTo({
        url: '../city2/city2',
      })
  },




  //商品分类切换
  GoodsTypeChange(e) {
    var t = this;
    var level = e.currentTarget.dataset.level;  //是几级分类切换操作
    var index = e.detail.value; //选择的下标

    var data = {
      goods_list: '',
      pnow: 1,
      NullNotice: true,
      NextStat: false,
    };
    switch (level) {
      case 1: case '1':
        data.g1_index = index;
        data.g2_index = 0;
        data.g3_index = 0;
        break;
      case 2: case '2':
        data.g2_index = index;
        data.g3_index = 0;
        break;
      case 3: case '3':
        data.g3_index = index;
        break;
    }
    t.setData(data);
  },







  //解析商户或商品信息
  GetInfoParse2(res, gs_type){
    var t = this;
    if (typeof res.data != 'object') {
      t.setData({
        store_list: [],
        goods_list: [],
        NullNotice: false
      });
      app.C('返回的商户或商品数据格式异常!');
      wx.hideLoading();
    } else if (res.data.length < 1) {
      t.setData({
        NextStat: true,
        store_list: [],
        goods_list: [],
        pnow: t.data.pnow - 1 > 1 ? t.data.pnow - 1:1,
      });
      wx.hideLoading();
    }else{
      for (var i = 0; i <res.data.length;i++){
        if(res.data[i][1]){
          var full_src = app.globalData.upyun_shop_img + res.data[i][1];
        }else{
          var full_src = app.globalData.default_img;
        }
        res.data[i][1] = full_src;
      }
      if (gs_type == 1) {
        if (res.data.length > 0) {
          t.setData({
            store_list: res.data,
            Fpage_stat: false,
            NextStat: false
          });
        } else {
          if (t.data.pnow == 1) {
            t.setData({
              NullNotice: false,
              //Fpage_stat: true,
              store_list: []
            });
          }
        }
      } else {
        if (res.data.length > 0) {
          t.setData({
            goods_list: res.data,
            Fpage_stat: false,
            NextStat: false
          });
        } else {
          if (t.data.pnow == 1) {
            t.setData({
              NullNotice: false,
              //Fpage_stat: true,
              goods_list: []
            });
          }
        }
      }

      wx.hideLoading();

    }
  },


  ImgErr(e){
    var index = e.target.dataset.index;
    var type = e.target.dataset.type;
    var t = this;
    if(type == 'goods'){
      var data = t.data.goods_list;
      data[index][1] = app.globalData.default_img;
      t.setData({
        goods_list:data
      });
    }else{
      var data = t.data.store_list;
      data[index][1] = app.globalData.default_img;
      t.setData({
        store_list: data
      });
    }
  },


  //点击分页码
  PageJump(e) {
    var t = this;
    if (!wx.getStorageSync('FpageExpire')) {
      app.SetStorage('FpageExpire', new Date().getTime());
    } else {
      var FpageExpire = parseInt(wx.getStorageSync('FpageExpire'));
      if (FpageExpire + 500 > new Date().getTime()) {
        return;
      } else {
        app.SetStorage('FpageExpire', new Date().getTime());
      }
    }
    var type = e.currentTarget.dataset.type;
    switch (type) {
      case 'first':
        if (t.data.pnow == 1) {
          return;
        }
        if(t.data.pnow > 1){
          var nextstat = 1;
        }
        var pnow = 1;
        break;
      case 'last':
        if (t.data.pnow == 1) {
          return;
        }
        if (t.data.pnow > 1) {
          var nextstat = 1;
        }
        var pnow = parseInt(t.data.pnow) - 1 <= 0 ? 1 : parseInt(t.data.pnow) - 1;
        break;
      case 'next':
        var pnow = parseInt(t.data.pnow) + 1;

        //判断是否到达缓存中的最大页
        var max_tag = t.data.current_page_tag;
        if (wx.getStorageSync(max_tag)) {
          var tag = wx.getStorageSync(max_tag)
          if(tag.time > new Date().getTime()){  //未过期
            if (t.data.pnow >= tag.max){
              t.setData({
                NextStat: true
              })
              return;
            }
          }else {
            app.SetStorage(max_tag, '');
          }
        }
        break;
    }
    if (nextstat){
      t.setData({
        pnow: pnow,
        NextStat: false
      })
    }else{
      t.setData({
        pnow: pnow,
      })
    }
  
    t.GetInfo();  //获取商户或商品数据
  },




})
